package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @version: 1.0
 * @Author: ljy
 * @description:
 * @date: 2025-07-31 14:47
 */
@Service
public class WechatServiceImpl implements WechatService {

    private static final String GET_OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    private static final String GET_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;

    @Override
    public String getOpenid(String code) {
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String result = HttpUtil.get(GET_OPENID_URL, params);
        //对结果进行解析
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjUtil.isNotEmpty(jsonObject.getInt("errcode"))) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("openid");
    }

    private String getAccessToken() {
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        String result = HttpUtil.get(GET_TOKEN_URL, params);
        //判断
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjUtil.isNotEmpty(jsonObject.getInt("errcode"))) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("access_token");
    }

    @Override
    public String getPhone(String detailCode) {
        //拼出请求的url
        String accessToken = this.getAccessToken();
        String url = GET_PHONE_URL + accessToken;
        Map<String, Object> params = new HashMap<>();
        params.put("code", detailCode);
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(params));//这里需要的是json数据
        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 判断接口响应是否出错
        if (jsonObject.getInt("errcode") != 0) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }
}
